const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');

//引入body-parser
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });

require('../models/UserModel.js');

const User = mongoose.model("User");

// 获取所有用户
router.get("/getusers",(req,res)=>{
    User.find({})
        .then(user=>{
          // res.send(JSON.stringify(user));
          res.json({//利用res将数据返回给get请求  
            code:200,
            data:user, 
            total:user.length, 
            msg:'查询成功',  
          })
        })
})

// 获取单个用户
router.get("/:id",(req,res)=>{
  User.find({_id:req.params.id})
      .then(user=>{
        res.json({ 
          code:200,
          data:user[0],  
          msg:'',  
        })
      })
})

// 搜索用户
router.post("/search",urlencodedParser,(req,res)=>{
  User.findOne({name:req.body.name})
      .then(user=>{
        res.json({ 
          code:200,
          data:user[0],  
          msg:'',  
        })
      })
})

// 添加用户
router.post("/adduser",urlencodedParser,(req,res)=>{
    const newUser = {
      name: req.body.name,
      tell:req.body.tell,
      email:req.body.email,
      educational:req.body.educational,
      school:req.body.school,
      profession:req.body.profession,
      describe:req.body.describe
    }
    new User(newUser)
        .save()
        .then((data)=>{
            res.send({
              code:200,
              msg:'用户添加成功'
            })
        })
})

// 修改用户
router.put("/updateuser/:id",urlencodedParser,(req,res)=>{
    User.findOne({
      _id:req.params.id
    }).then((newUser) => {
      newUser.name = req.body.name;
      newUser.tell = req.body.tell;
      newUser.email = req.body.email;
      newUser.educational = req.body.educational;
      newUser.school = req.body.school;
      newUser.profession = req.body.profession;
      newUser.describe = req.body.describe;
      newUser.save().then(() => {
      res.json({
          code:200,  
          msg:'用户修改成功',  
        })
      })
    })
})


// 删除
router.delete("/delete/:id",(req,res)=>{
  User.remove({
      _id:req.params.id
  }).then(idea=>{
    res.json({
      code:200,  
      msg:'用户删除成功',  
    })
  })
})

/////////
module.exports = router;
